/*
 * BetterUtility.cpp
 *
 *  Created on: 2011-3-22
 *      Author: wangchao
 */

#include "BetterUtility.h"
#include "core_defines.h"

//#include "fWml.h"

void BetterUtility::Copy( HBufC*& dest, const TDesC & text )
{
    int length = text.Length( );

    if( length > 0 )
    {
        if( dest && length < dest->Des( ).MaxLength( ) )
        {
            dest->Des( ).Copy( text );
        }
        else
        {
            SAFE_DELETE( dest );
            dest = text.Alloc( );
        }
    }
    else
    {
        if( dest )
        {
            dest->Des( ).Zero( );
        }
    }

}

void BetterUtility::Append( HBufC*& dest, const TDesC & text )
{
    int length = text.Length( );
    if( length > 0 )
    {
        if( dest )
        {
            int newLength = length + dest->Length( );
            if( newLength < dest->Des( ).MaxLength( ) )
            {
                dest->Des( ).Append( text );
            }
            else
            {
                dest = dest->ReAlloc( newLength );
                dest->Des( ).Append( text );
            }
        }
        else
        {
            dest = text.Alloc( );
        }
    }

}
/*
HBufC* BetterUtility::GetNotNullElementText( CElement* element )
{
    return element ? element->GetElmentText( ).Alloc( ) : KNullDesC( ).Alloc( );
}

HBufC* BetterUtility::GetElementText( CElement* element )
{
    return element ? element->GetElmentText( ).Alloc( ) : NULL;
}

bool BetterUtility::CompareElementText( CElement* element, const TDesC& toCompare )
{
    if( element )
    {
        return element->GetElmentText( ) == toCompare;
    }
    else
    {
        return false;
    }
}

int BetterUtility::GetElementTextAsInt( CElement* element )
{
    return element ? element->GetElementTextAsInt( ) : -1;
}*/

HBufC* BetterUtility::AllocNotNull( HBufC* sour )
{
    return sour ? sour->Alloc( ) : KNullDesC( ).Alloc( );
}

HBufC* BetterUtility::Alloc( HBufC* sour )
{
    return sour ? sour->Alloc( ) : NULL;
}

bool BetterUtility::IsNullOrEmpty( const HBufC* text )
{
    return ( !text || text->Length( ) < 1 );
}

int BetterUtility::CalcPercentValue( int percent, int total, int totalValue )
{
    _ASSERT_LOG( total != 0 );
    if( percent == 0 || totalValue == 0 )
    {
        return 0;
    }
    else if( percent == total )
    {
        return totalValue;
    }
    else
    {
        return percent * totalValue / total;
    }
}
